<template>
    <el-dialog v-model="props.visible" width="30%" title="编辑合同" @close="handleClose" destroy-on-close>
        <el-form :model="formData" ref="formRef" :rules="rules">
            <el-row :gutter="50">
                <el-col :span="12">
                    <el-form-item label="客户名称">
                        <el-select :style="{width:'100%'}" v-model="customerInfo" value-key="id">
                            <el-option v-for="item in props.customers" :label="item.customerName" :value="item"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12"></el-col>
            </el-row>
            <el-row :gutter="50">
                <el-col :span="12">
                    <el-form-item label="合同总额" prop="contractAmount">
                        <el-input v-model="formData.contractAmount" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="合同定金" prop="contractDeposit">
                        <el-input v-model="formData.contractDeposit" placeholder="请输入" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="50">
                <el-col :span="12">
                    <el-form-item label="签约时间" prop="signDate">
                        <el-date-picker type="date" placeholder="签约时间" v-model="formData.signDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="终止时间" prop="endDate">
                        <el-date-picker type="date" placeholder="终止时间" v-model="formData.endDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="上传合同" prop="fileUrl">
                <el-upload class="upload-demo" 
                    drag 
                    multiple
                    ref="uploadRef"
                    :action="uploadImgUrl"
                    :headers="headers"
                    :before-upload="beforeAvatarUpload" 
                    :on-success="handleAvatarSuccess"
                    v-model:file-list="fileList"
                >
                    <el-icon class="el-icon--upload"><Plus /></el-icon>
                    <div class="el-upload__text">点击或拖拽文件到此处上传</div>
                    <template #tip>
                        <div class="el-upload__tip">
                            文件不超过10MB
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input type="textarea" maxlength="128" show-word-limit v-model="formData.remark" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button  type="primary" @click="handleSubmit(formRef)">确 定</el-button>
                <el-button @click="handleClose">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance,UploadInstance, UploadProps,FormRules,UploadUserFile } from 'element-plus';
import { editContractApi } from '@/api/sj/contract-crm/index';
import { Plus } from '@element-plus/icons-vue';
import { globalHeaders } from "@/utils/request";

const props = defineProps(['visible','data','customers']);
const emits = defineEmits(['close','submit']);
const formRef = ref<FormInstance>();
const uploadRef = ref<UploadInstance>();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);
const customerInfo = ref<any>();
const formData = ref({
    contractAmount: undefined,
    contractDeposit: undefined,
    signDate: undefined,
    endDate: undefined,
    fileUrl: undefined,
    remark: undefined
});

const fileList = ref<UploadUserFile[]>([])

watch(()=>props.data,()=>{
    formData.value = props.data;
    customerInfo.value = {
        id: props.data.customerId,
        customerName: props.data.customerName
    };
    fileList.value.push({name: 'image',url:props.data.fileUrl});
},{deep:true});

const handleSubmitEdit = async (data: any)=>{
    const result = await editContractApi(data);
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error('图片大小不可超过 10MB!')
        return false;
    }
    return true;
};

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response
    ) => {
        formData.value.fileUrl = response.data.url;
};

const rules = reactive<FormRules>({
    customer:[
        {
            required: true,
            trigger: 'blur',
            message:'请选择客户'
        }
    ],
    totalAmount:[
        {
            required: true,
            trigger: 'blur',
            message: '请输入合同总额'
        }
    ],
    depositAmount:[
        {
            required: true,
            trigger: 'blur',
            message: '请输入合同定金'
        }
    ],
    signDate: [
        {
            required: true,
            trigger: 'blur',
            message: '请选择合同开始时间'
        }
    ],
    endDate: [
        {
            required: true,
            trigger: 'blur',
            message: '请选择终止时间'
        }
    ],
    uploadContract: [
        {
            required: true,
            trigger: 'blur',
            message: '未上传合同，无法保存'
        }
    ]
});

const handleClose = ()=>{
    formRef.value?.resetFields();
    uploadRef.value?.clearFiles();
    fileList.value = [];
    emits('close');
};

const handleSubmit = async (formEl: FormInstance | undefined)=>{
    if(!formEl) return;
    await formEl.validate((valid, fields)=>{
        if(valid){
            const submitData = {...formData.value,customerId: customerInfo.value.id,customerName: customerInfo.value.customerName};
            handleSubmitEdit(submitData).then((result)=>{
                emits('submit', true);
                handleClose();
            });
        }else{
            console.log('error submit!', fields)
        };
    });
};

</script>

<style lang="scss" scoped>
.upload-demo{
    width: 35%;
}
::v-deep(.el-input__wrapper){
    width:100%
}
</style>